from text2vec import SentenceModel
import numpy as np
from rank_bm25 import BM25Okapi
import jieba
from Levenshtein import ratio

def find_most_similar(sentence: str, phrases: list[str], threshold=0.8, min_diff=0.15) -> str:
    clean_input = sentence.strip()
    
    # 计算所有短语的相似度
    scores = [ratio(clean_input, phrase) for phrase in phrases]
    max_score = max(scores)
    max_index = scores.index(max_score)
    
    # 获取次高分
    second_score = sorted(scores, reverse=True)[1] if len(phrases) >1 else 0
    
    print(f"最高相似度: {max_score:.2f}, 次高: {second_score:.2f}")
    
    # 双重判断条件
    if max_score >= threshold and (max_score - second_score) >= min_diff:
        return phrases[max_index]
    return None

# 移除所有模型相关依赖
# 测试循环保持不变

# 示例词组保持不变
test_phrases = ["前进", "后退", "左转", "右转","停下"]

while True:
    user_input = input("\n请输入指令语句（输入exit退出）: ").strip()
    if user_input.lower() in ('exit', '退出'):
        print("程序已退出")
        break
    if not user_input:
        continue
    
    # 获取并打印结果（修改输出判断）
    result = find_most_similar(user_input, test_phrases)
    if result:
        print(f">> 匹配结果：{result}")
    else:
        print(">> 无有效匹配")